import { currentShape } from '../data/shapes';
import { currentStage } from '../data/stage';

export class UndoManager {
  history: Array<any>;

  index: number;

  constructor() {
    this.history = [];
    this.index = -1;
  }

  save() {
    const record = JSON.stringify(currentStage.value.components);
    const isExist = this.history.findIndex(item => {
      if (record === item) {
        return true;
      }
      return null;
    });
    if (isExist < -1) {
      this.history.push(record);
      this.index += 1;
    }
  }

  redo() {
    if (!this.history[this.index]) return;
    if (this.index > 0) {
      this.index -= 1;
    } else if (this.index === 0) {
      currentStage.value.components = [];
      return;
    }
    currentStage.value.components = JSON.parse(this.history[this.index] || []);
    currentShape.value.id = '';
  }

  undo() {
    if (!this.history[this.index]) return;
    if (this.index >= 50) {
      this.history.shift();
    } else if (this.index < this.history.length - 1) {
      this.index += 1;
    }
    currentStage.value.components = JSON.parse(this.history[this.index] || []);
    currentShape.value.id = '';
  }
}

export const unredo = new UndoManager();
